package org.tof.hotel.csv;

import org.apache.log4j.Logger;
import org.tof.hotel.exception.FileIsEmptyException;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class CSVParser {
    private char delimiter;
    private static Logger logger = Logger.getLogger(CSVParser.class.getName());

    /**
     * Uses comma as a delimiter
     */
    public CSVParser() {
        this.delimiter = ',';
    }

    public CSVParser(char delimiter) {
        this.delimiter = delimiter;
    }

    /**
     * Returns array of both field names and field values
     *
     * @param filename name of the file to parse
     * @return List of string arrays
     *         <P>where first array - field names and
     *         <P>each other contains field values of one object
     */
    public ArrayList<String[]> parse(String filename) {
        ArrayList<String[]> strings = new ArrayList<String[]>();
        Scanner scanner = null;
        try {
            scanner = new Scanner(new File(filename));
            if (!scanner.hasNextLine()) {
                throw new FileIsEmptyException(filename);
            }
            while (scanner.hasNextLine()) {
                strings.add(CSVStringToFields(scanner.nextLine()));
            }
        } catch (FileIsEmptyException e) {
            logger.error(e.toString(), e);
        } catch (FileNotFoundException e) {
            logger.error(e.toString(), e);
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
        return strings;
    }

    /**
     * Returns ArrayList<String> of object field values
     *
     * @param CSVString string with field values in comma-separated format
     * @return ArrayList<String> of field values
     */
    public String[] CSVStringToFields(String CSVString) {
        return CSVString.split(Character.toString(delimiter));
    }
}
